//
//  ApartmentHotelViewController.m
//  House
//
//  Created by 张垚 on 16/6/28.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "ApartmentHotelViewController.h"
#import "SearchHouseViewController.h"
#import "ApartmentHotelListTableViewCell.h"
#import "AgentListTableViewCell.h"
#import "LrdSuperMenu.h"
#import "BaseNavigationBar.h"
#import "MySearchBar.h"
#import "ApartmentHotelDetailViewController.h"
#import "ReuseSelectButtonView.h"
#import "AreaAndTypeChooseViewController.h"
#import "PriceChooseViewController.h"
#import "ApartmentHotelListModel.h"


@interface ApartmentHotelViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *titleArray;

@property (nonatomic, copy) NSString *urlString;
@property (nonatomic, strong) NSMutableArray *dataDicArr;

@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) MBProgressHUD *selectHud;

@end

static NSString *urlStr = @"http://aizufang.hrbzjwl.com/tp/api.php/Gongyujd/index/";
static NSString *areaStr = @"不限";
static NSString *priceStr = @"不限";
static NSString *typeStr = @"不限";
static NSString *houseTypeStr = @"不限";
//页数
static NSInteger page = 1;
//是否进行过区域选择
static NSInteger tag = 1;

@implementation ApartmentHotelViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 主程序入口

- (void)viewDidLoad {
    [super viewDidLoad];
     self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self initTableView];
    [self initLrdSuperMenu];
    [self getHotelListData];
    [self setHeaderRefresh];
   //菊花属性设置
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.label.text = @"正在加载数据";
    _hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.backgroundView.backgroundColor = [UIColor whiteColor];
    _hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    _hud.animationType = MBProgressHUDAnimationZoomIn;
    // Do any additional setup after loading the view.
}

#pragma mark - 导航栏搜索
/* 重写父类方法 */
- (void)initNavigationBar {
    [super initNavigationBar];
    self.myBar.searchBar.textFiled.placeholder = @"请输入酒店名";
    [self.myBar.searchBar.textFiled setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    UITapGestureRecognizer *popTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pop:)];
    [self.myBar.leftView addGestureRecognizer:popTap];
    UITapGestureRecognizer *pushSearchHouseTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(push)];
    [self.myBar.searchBar addGestureRecognizer:pushSearchHouseTap];
}

//返回上一层级
- (void)pop:(UITapGestureRecognizer *)tap {
    [self.navigationController popViewControllerAnimated:YES];
}

/* 点击搜索栏 跳转页面进行搜索 */
- (void)push {
    SearchHouseViewController *searchVC = [[SearchHouseViewController alloc] init];
    searchVC.currentStr = @"公寓酒店";
    [self.navigationController pushViewController:searchVC animated:YES];
}


#pragma mark - 数据请求
//第一页数据显示
- (void)getHotelListData {
    _dataDicArr = [NSMutableArray array];
    [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/api.php/Gongyujd/index/" parameters:@{@"areaid": [[NSUserDefaults standardUserDefaults] objectForKey:cityID], @"page": @"1"} progress:^(NSProgress *progress) {
        
    } success:^(id response) {
        if ([response[@"flag"] isEqualToString:@"1"]) {
            _hud.label.text = @"加载成功";
            [_hud hideAnimated:YES afterDelay:1];
            _dataDicArr = response[@"list"];
            [_tableView reloadData];
        }else {
            _hud.label.text = @"加载失败";
            [_hud hideAnimated:YES afterDelay:1];
        }
    } failure:^(NSError *error) {
        _hud.label.text = @"服务器异常";
        [_hud hideAnimated:YES afterDelay:1];
    }];
    [self setFooterRefresh];
}

//条件之后 请求数据
- (void)handleDataWithSelectUrlString:(NSString *)selectUrlString {
    _selectHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _selectHud.label.text = @"加载中...";
    _selectHud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    _selectHud.animationType = MBProgressHUDAnimationZoomIn;
    //获取第一页
    NSString *urlStr = [NSString stringWithFormat:@"%@page/1/areaid/%@", selectUrlString, [[NSUserDefaults standardUserDefaults] objectForKey:cityID]];
    [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
        
    } success:^(id response) {
        if ([[response[@"flag"] description] isEqualToString:@"0"]) {
            UIImage *image = [[UIImage imageNamed:@"failIcon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            _selectHud.mode = MBProgressHUDModeCustomView;
            _selectHud.customView = imageView;
            _selectHud.label.text = @"暂无此类型房源";
            [_selectHud hideAnimated:YES afterDelay:1];
            _dataDicArr = [NSMutableArray array];
            [_tableView reloadData];
        }else {
            UIImage *image = [[UIImage imageNamed:@"successIcon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            _selectHud.mode = MBProgressHUDModeCustomView;
            _selectHud.customView = imageView;
            _selectHud.label.text = @"筛选成功";
            [_selectHud hideAnimated:YES afterDelay:1];
            //将获取的值赋给数据 刷新tableview
            NSArray *arr = response[@"list"];
            _dataDicArr = [NSMutableArray arrayWithArray:arr];
            [_tableView reloadData];
        }
    } failure:^(NSError *error) {
        UIImage *image = [[UIImage imageNamed:@"failIcon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        _selectHud.mode = MBProgressHUDModeCustomView;
        _selectHud.customView = imageView;
        _selectHud.label.text = @"服务器异常，请重试";
        [_selectHud hideAnimated:YES afterDelay:1];
    }];
    [self setFooterRefresh];
}

//下拉刷新
- (void)setHeaderRefresh {
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (tag == 1) {
            [self getHotelListData];
        }else {
            [self handleDataWithSelectUrlString:_urlString];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView.mj_header endRefreshing];
        });
    }];
}

//上拉加载
- (void)setFooterRefresh {
    //判断下拉刷新的是所有数据 还是经过条件筛选之后的数据
    if (tag == 1) {
        [self.tableView.mj_footer beginRefreshing];
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            //每刷一次 请求的页数叠加
            page++;
            NSDictionary *dic = @{@"page": [NSString stringWithFormat:@"%ld", (long)page], @"areaid": [[NSUserDefaults standardUserDefaults] objectForKey:cityID]};
            //网络请求数据
            [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/api.php/Gongyujd/index/" parameters:dic progress:^(NSProgress *progress) {
            } success:^(id response) {
                //没有数据 显示已加载全部数据
                if ([response[@"flag"] isEqualToString:@"0"] ) {
                    self.tableView.mj_footer = nil;
                }
                //否则数据一直叠加并且刷新tableview显示
                else {
                    for (NSDictionary *dic in response[@"list"]) {
                        [_dataDicArr addObject:dic];
                    }
                    [_tableView reloadData];
                    [self.tableView.mj_footer endRefreshing];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@", error);
            }];
        }];
        
    }else {
        [self.tableView.mj_footer beginRefreshing];
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            //每刷一次 请求的页数叠加
            page++;
            //网络请求数据
            [NetRequest getWithURLString:_urlString parameters:@{@"page": [NSString stringWithFormat:@"%ld", (long)page], @"areaid": [[NSUserDefaults standardUserDefaults] objectForKey:cityID]} progress:^(NSProgress *progress) {
            } success:^(id response) {
                //没有数据 显示已加载全部数据
                if ([response[@"flag"] isEqualToString:@"0"]) {
                    self.tableView.mj_footer = nil;
                }
                //否则数据一直叠加并且刷新tableview显示
                else {
                    for (NSDictionary *dic in response[@"list"]) {
                        [_dataDicArr addObject:dic];
                    }
                    [_tableView reloadData];
                    [self.tableView.mj_footer endRefreshing];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@", error);
            }];
        }];
    }
}

#pragma mark - 筛选条件 字段处理
//区域选择视图创建
- (void)initLrdSuperMenu {
    ReuseSelectButtonView *selectView = [[ReuseSelectButtonView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 40) WithButtonTitleArr:@[@"区域", @"价格", @"类型", @"房型"]];
    selectView.backgroundColor = [UIColor whiteColor];
    [selectView.areaButton addTarget:self action:@selector(selectData:) forControlEvents:UIControlEventTouchUpInside];
    [selectView.priceButton addTarget:self action:@selector(selectData:) forControlEvents:UIControlEventTouchUpInside];
    [selectView.typeButton addTarget:self action:@selector(selectData:) forControlEvents:UIControlEventTouchUpInside];
    [selectView.moreButton addTarget:self action:@selector(selectData:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:selectView];
}


//筛选按钮点击事件
- (void)selectData:(UIButton *)button {

    switch (button.tag) {
        case 100:
        {
            AreaAndTypeChooseViewController *areaVC = [[AreaAndTypeChooseViewController alloc] init];
            areaVC.tag = button.tag;
            areaVC.currentStr = button.titleLabel.text;
            [areaVC passInfoToPreviousPage:^(NSString *currentStr, NSInteger currentTag) {
                if ([currentStr isEqualToString:@"不限"]) {
                    [button setTitle:@"区域" forState:UIControlStateNormal];
                    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                }else {
                    [button setTitle:currentStr forState:UIControlStateNormal];
                    [button setTitleColor:KNaviBackColor forState:UIControlStateNormal];
                }
                areaStr = currentStr;
                [self getSelectDataWithAreaString:areaStr withPriceString:priceStr WithTypeString:typeStr WithHouseTypeString:houseTypeStr];
            }];
            [self.navigationController pushViewController:areaVC animated:YES]; 
        }
            break;
        case 101:
        {
            AreaAndTypeChooseViewController *areaVC = [[AreaAndTypeChooseViewController alloc] init];
            areaVC.tag = 1;
            areaVC.currentStr = button.titleLabel.text;
            [areaVC passSubmitInfoToPreviousPage:^(NSString *currentStr, NSString *submitStr) {
                if ([currentStr isEqualToString:@"不限"]) {
                        [button setTitle:@"价格" forState:UIControlStateNormal];
                        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                }else {
                        [button setTitle:currentStr forState:UIControlStateNormal];
                        [button setTitleColor:KNaviBackColor forState:UIControlStateNormal];
                                    }
                priceStr = submitStr;
                [self getSelectDataWithAreaString:areaStr withPriceString:priceStr WithTypeString:typeStr WithHouseTypeString:houseTypeStr];
            }];
           
            [self.navigationController pushViewController:areaVC animated:YES];
        }
            break;
        case 102:
        {
            AreaAndTypeChooseViewController *areaVC = [[AreaAndTypeChooseViewController alloc] init];
            areaVC.tag = 2;
            areaVC.currentStr = button.titleLabel.text;
            [areaVC passInfoToPreviousPage:^(NSString *currentStr, NSInteger currentTag) {
                if ([currentStr isEqualToString:@"不限"]) {
                    [button setTitle:@"类型" forState:UIControlStateNormal];
                    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                }else {
                    [button setTitle:currentStr forState:UIControlStateNormal];
                    [button setTitleColor:KNaviBackColor forState:UIControlStateNormal];
                }
                typeStr = currentStr;
                [self getSelectDataWithAreaString:areaStr withPriceString:priceStr WithTypeString:typeStr WithHouseTypeString:houseTypeStr];
            }];
            
             [self.navigationController pushViewController:areaVC animated:YES];
        }
            break;
        case 103:
        {
            AreaAndTypeChooseViewController *areaVC = [[AreaAndTypeChooseViewController alloc] init];
            areaVC.tag = 3;
            areaVC.currentStr = button.titleLabel.text;
            [areaVC passInfoToPreviousPage:^(NSString *currentStr, NSInteger currentTag) {
                if ([currentStr isEqualToString:@"不限"]) {
                    [button setTitle:@"房型" forState:UIControlStateNormal];
                    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                }else {
                    [button setTitle:currentStr forState:UIControlStateNormal];
                    [button setTitleColor:KNaviBackColor forState:UIControlStateNormal];
                }
                houseTypeStr = currentStr;
                 [self getSelectDataWithAreaString:areaStr withPriceString:priceStr WithTypeString:typeStr WithHouseTypeString:houseTypeStr];
            }];
            [self.navigationController pushViewController:areaVC animated:YES];
          
        }
            break;
        default:
            break;
    }
    
}

//拼接筛选条件 拼接出新的URL 请求数据进行显示
- (void)getSelectDataWithAreaString:(NSString *)areaString withPriceString:(NSString *)priceString WithTypeString:(NSString *)typeString WithHouseTypeString:(NSString *)houseTypeString  {
    NSString *urlStr = @"http://aizufang.hrbzjwl.com/tp/api.php/Gongyujd/index/";
    if (![areaString isEqualToString:@"不限"]) {
        areaString = [areaString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
        urlStr = [NSString stringWithFormat:@"%@area/%@/",urlStr, areaString];
    }
    if (![priceString isEqualToString:@"不限"]) {
        priceString = [priceString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
        urlStr = [NSString stringWithFormat:@"%@price/%@/",urlStr, priceString];
    }
    if (![typeString isEqualToString:@"不限"]) {
        typeString = [typeString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
        urlStr = [NSString stringWithFormat:@"%@type/%@/",urlStr, typeString];
    }
    if (![houseTypeString isEqualToString:@"不限"]) {
        houseTypeString = [houseTypeString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
        urlStr = [NSString stringWithFormat:@"%@room/%@/",urlStr, houseTypeString];
    }
    page = 1;
    tag = 2;
    //下拉刷新 赋值新的url 修改标签值 进行判断
    _urlString = urlStr;
    //拼接之后显示数据
    [self handleDataWithSelectUrlString:urlStr];
}

#pragma mark - tableView
//初始化
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 108, self.view.frame.size.width, kScreenHeight - 108) style:UITableViewStylePlain];
    _tableView.tableFooterView = [UIView new];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[ApartmentHotelListTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ApartmentHotelListTableViewCell class])];
    
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [tableView placeholderBaseOnNumber:_dataDicArr.count iconConfig:^(UIImageView *imageView) {
        // 传入一个想展示的图标
        imageView.image = [UIImage imageNamed:@"emptyTableView"];
    } textConfig:^(UILabel *label) {
        // 设置提示性文字
        label.text      = @"未找到符合条件的酒店公寓";
        label.textColor = [UIColor lightGrayColor];
        label.font      = [UIFont systemFontOfSize:15];
    }];
    return _dataDicArr.count;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ApartmentHotelListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ApartmentHotelListTableViewCell class])];
    NSDictionary *dic = _dataDicArr[indexPath.row];
    ApartmentHotelListModel *model = [ApartmentHotelListModel modelWithDic:dic];
    cell.model = model;
    cell.tag = [model.itemid integerValue];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
//cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ApartmentHotelListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    ApartmentHotelDetailViewController *apartVC = [[ApartmentHotelDetailViewController alloc] init];
    apartVC.hotelID = [NSString stringWithFormat:@"%ld", (long)cell.tag];
    apartVC.titleStr = cell.model.housename;
    [self.navigationController pushViewController:apartVC animated:YES];
}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
